package com.colt.usercenter.controller.user;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.http.HttpStatus;
import com.colt.usercenter.auth.CheckLogin;
import com.colt.usercenter.domain.dto.user.*;
import com.colt.usercenter.domain.entity.user.User;
import com.colt.usercenter.security.RegistorExcepion;
import com.colt.usercenter.service.user.impl.UserServiceImpl;
import com.colt.usercenter.util.JwtOperator;
import com.colt.usercenter.util.RequestUtil;
import com.colt.usercenter.util.response.BaseResponse;
import com.colt.usercenter.util.response.ResponseData;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: user-center
 * @description: userController
 * @author: colt
 * @create: 2020-05-02 10:27
 **/
@Slf4j
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserController {
    private final UserServiceImpl userService;
    private final WxMaService wxMaService;
    private final JwtOperator jwtOperator;

    /*
    * 模拟生成token
    * */
    @GetMapping("gen-token")
    public String genTOken(){
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("id",1);
        userInfo.put("wxNickName","colka");
        userInfo.put("role","admin");
        return this.jwtOperator.generateToken(userInfo);

    }
    @CheckLogin
    @PostMapping("/sign")
    public BaseResponse<Object> sign(){
        UserResponseDTO sign = userService.sign();
        return  BaseResponse.builder()
                .msg("签到成功")
                .code(HttpStatus.HTTP_ACCEPTED)
                .data(sign)
                .build();
    }
    @CheckLogin
    @GetMapping("/{id}")
    public User findById(@PathVariable Integer id){ //@PathVariable  获取占位符的值
        return this.userService.findById(id);
    }
    @GetMapping("/test-get")
    public User query(User user){ //@PathVariable  获取占位符的值
        return user;
        //return this.userService.query(user);
    }
    @ResponseBody
    @PostMapping("/loginByPwd")
    public LoginResponseDTO loginByPassword(@RequestBody UserRegistorDTO userLoginDTO){
        /** 
        * @Description: 通过账号密码登录 
        * @Param: [userLoginDTO] 
        * @return: com.colt.usercenter.domain.dto.user.LoginResponseDTO 
        * @Author: colt 
        * @Date: 2020/9/21 
        */
        User user = userService.loginByUsername(userLoginDTO);
        //颁发token
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("id",user.getId());
        userInfo.put("wxNickName",user.getWxNickname());
        userInfo.put("role",user.getRoles());
        String token = jwtOperator.generateToken(userInfo);
        log.info(
                "用户{}登录成功，已获取token：{}，有效期到：{}",
                user.getWxNickname(),
                token,
                jwtOperator.getExpirationTime().getTime());
        return LoginResponseDTO.builder()
                .userResponseDTO(
                        UserResponseDTO.builder()
                        .wxNickName(user.getWxNickname())
                        .avatarUrl(user.getUsername())
                        .bonus(user.getBonus())
                        .build()
                ).token(JwtTokenResponseDTO.builder()
                .token(jwtOperator.generateToken(userInfo))
                        .expirationTime(jwtOperator.getExpirationTime().getTime())
                        .build()
                ).build();

    }
    @PostMapping("/registry")
    public User registry(@RequestBody UserRegistorDTO userRegistorDTO){
        /**
        * @Description: 通过账号密码注册
        * @Param: [userLoginDTO]
        * @return: com.colt.usercenter.domain.dto.user.LoginResponseDTO
        * @Author: colt
        * @Date: 2020/9/21
        */
        User userList = this.userService.findByUsername(userRegistorDTO);
        if (userList!=null){
            throw new RegistorExcepion();
        }
        User user = userService.insertUserInfo(userRegistorDTO);
        return user;
    }

    @PostMapping("/login")
    public LoginResponseDTO loginByWeChat(@RequestBody UserLoginDTO userLoginDTO) throws WxErrorException {
        /**
        * @Description: 通过微信小程序注册登录
         * @Param: [userLoginDTO]
        * @return: com.colt.usercenter.domain.dto.user.LoginResponseDTO
        * @Author: colt
        * @Date: 2020/9/21
        */
       /* 用code请求微信api,验证已登录微信小程序，如果用户已注册，颁发token，返回用户信息
        若未注册，进行注册操作，颁发token，返回用户信息。*/
       //微信小程序服务端校验是否登录的结果
        WxMaJscode2SessionResult result = this.wxMaService.getUserService()
                .getSessionInfo(userLoginDTO.getCode());

//        若已登录 获取openId,用户在微信的唯一标识
        String openid = result.getOpenid();
//        看用户是否注册，若没就注册就插入,
        User user = this.userService.Login(userLoginDTO, openid);
 //       颁发token
        Map<String,Object> userInfo = new HashMap<>();
        userInfo.put("id",user.getId());
        userInfo.put("wxNickName",user.getWxNickname());
        userInfo.put("role",user.getRoles());
        String token = jwtOperator.generateToken(userInfo);

        log.info(
                "用户{}登录成功，已获取token：{}，有效期到：{}",
                userLoginDTO.getWxNickname(),
                token,
                jwtOperator.getExpirationTime().getTime());
//        构建响应
        return LoginResponseDTO.builder()
                .userResponseDTO(
                        UserResponseDTO.builder()
                        .id(user.getId())
                        .avatarUrl(user.getAvatarUrl())
                        .wxNickName(user.getWxNickname())
                        .bonus(user.getBonus())
                        .build()
                )
                .token(
                        JwtTokenResponseDTO.builder()
                        .expirationTime(jwtOperator.getExpirationTime().getTime())
                        .token(token)
                        .build()
                ).build();
    }
}
